﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using MINERP.COM;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Xml;

namespace MINERP.NewProductBigPic
{
    static class Program
    {
        static string receiveMsgFromServer;
        static bool isNeedReboot;

        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
           
            //UDPMessage.EncryptConfiguration();
            bool isAppRunning = false;
            System.Threading.Mutex mutex = new System.Threading.Mutex(
                true,
                "productaaa",
                out isAppRunning);

            if (!isAppRunning)
            {
                MessageBox.Show("本程序已运行，请不要重复运行！");
                Environment.Exit(1);
            }
            else
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                Application.ApplicationExit += new EventHandler(Application_ApplicationExit);
                
                Application.ThreadException += new ThreadExceptionEventHandler(UIThreadException);
                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

                if (isNeedReboot)
                {
                    Application.Exit();
                }
                else
                {
                    try
                    {
                       // MessageBox.Show("2222");
                        receiveMsgFromServer = UDPMessage.GetServerInfo()[0];
                        ProcessReceiveMsg();
                        RegDLL();
                        Application.Run(new FrmBigPic());
                    }
                    catch (Exception)
                    {
                        
                        throw;
                    }
                   
                }

            }
        }
        private static void UIThreadException(object sender, ThreadExceptionEventArgs t)
        {
            try
            {
                string errorMsg = "Windows窗体线程异常 : \n\n";
                WriteLogForCheck.WriteLogFile(DateTime.Now + ":" + errorMsg + t.Exception.Message + Environment.NewLine + t.Exception.StackTrace);
            }
            catch
            {
                MessageBox.Show("不可恢复的Windows窗体异常，应用程序将退出！");
            }
        }
        static void RegDLL()
        {
            Process.Start("regsvr32", string.Format("/s \"{0}\"", Path.Combine(Environment.CurrentDirectory, "ImageEnXLibrary.ocx")));
            Process.Start("regsvr32", string.Format("/s \"{0}\"", Path.Combine(Environment.CurrentDirectory, "ET199Com.dll")));
            Process.Start("regsvr32", string.Format("/s \"{0}\"", Path.Combine(Environment.CurrentDirectory, "LayoutDll.dll")));
            Process.Start("regsvr32", string.Format("/s \"{0}\"", Path.Combine(Environment.CurrentDirectory, "RealLayoutPanel.ocx")));
            Process.Start("regsvr32", string.Format("/s \"{0}\"", Path.Combine(Environment.CurrentDirectory, "MarkImageDll.dll")));

        }
        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            try
            {
                Exception ex = (Exception)e.ExceptionObject;
                string errorMsg = "非窗体线程异常 : \n\n";
                WriteLogForCheck.WriteLogFile(DateTime.Now + ":" + errorMsg + ex.Message + Environment.NewLine + ex.StackTrace);
            }
            catch
            {
                MessageBox.Show("不可恢复的非Windows窗体线程异常，应用程序将退出！");
            }
        }
        static void Application_ApplicationExit(object sender, EventArgs e)
        {
            //程序正常结否时处理是否需要重启
            if (isNeedReboot)
            {
                Process.Start(Application.ExecutablePath);
            }
        }

        /// <summary>
        /// 每次启动时处理收到的信息
        /// </summary>
        static void ProcessReceiveMsg()
        {
            List<string> recMsgList = receiveMsgFromServer.Split(new char[] { '|' }).ToList();
            string curConnStr = ConfigurationManager.ConnectionStrings["sqlCon"].ConnectionString;
            string serverConnStr = recMsgList[0];
            if (!serverConnStr.Equals(curConnStr))//如果不等
            {
                ModifyConfig(serverConnStr);
                isNeedReboot = true;
            }

            //检查IP地址是否相等
            CheckIpIsModify(recMsgList[1]);
        }

        private static void CheckIpIsModify(string serverName)
        {
            int startIndex = serverName.IndexOf("(");
            string ip = serverName.Substring(startIndex + 1, serverName.Length - startIndex-2);
            if (!ConfigurationManager.AppSettings["RemoteIP"].Equals(ip))
            {
                ModifyConfigurationOP.SetConfig("RemoteIP", ip);
                isNeedReboot = true;
            }
        }


        //修改连接配置
        private static void ModifyConfig(string strConn)
        {
            //修改Printing
            ConnectionStringSettings mySettings1 = new ConnectionStringSettings("sqlCon", strConn, "System.Data.SqlClient");
            System.Configuration.Configuration config1 = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config1.ConnectionStrings.ConnectionStrings.Remove("sqlCon");
            config1.ConnectionStrings.ConnectionStrings.Add(mySettings1);
            config1.Save(ConfigurationSaveMode.Minimal);
            ConfigurationManager.RefreshSection("ConnectionStrings");


            //修改newSampleYPDBEntities
            string connectionString = ConfigurationManager.ConnectionStrings["newSampleYPDBEntities"].ToString();
            string strConn1 = strConn + ";";
            string strConn2 = string.Empty;
            strConn2 = connectionString.Substring(connectionString.IndexOf("MultipleActiveResultSets"));
            string str = connectionString.Substring(0, connectionString.IndexOf("Data Source"));
            connectionString = str + strConn1 + strConn2;
            ConnectionStringSettings mySettings = new ConnectionStringSettings("newSampleYPDBEntities", connectionString, "System.Data.EntityClient");
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.ConnectionStrings.ConnectionStrings.Remove("newSampleYPDBEntities");
            config.ConnectionStrings.ConnectionStrings.Add(mySettings);
            config.Save(ConfigurationSaveMode.Minimal);
            ConfigurationManager.RefreshSection("ConnectionStrings");
        }
    }
}
